package com.wxzz.elearing.user.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import com.wxzz.elearing.user.amqp.producer.UserMessageProducer;
import com.wxzz.elearing.user.dto.*;
import com.wxzz.elearing.user.entity.*;
import com.wxzz.elearing.user.mapper.*;
import com.wxzz.elearing.user.service.*;
import com.wxzz.elearing.user.service.openfeign.ICurriculumApiFeign;
import com.wxzz.elearing.user.service.openfeign.ILivetelecastApiFeign;
import com.wxzz.elearing.user.service.openfeign.IUserWalletApiFeign;
import com.wxzz.elearing.user.vo.DocentToolFileVo;
import com.wxzz.elearing.user.vo.DocentTrialFileVo;
import com.wxzz.elearning.common.bean.SmsConfig;
import com.wxzz.elearning.common.constants.RedisConstants;
import com.wxzz.elearning.common.dto.FeignUserWalletDto;
import com.wxzz.elearning.common.dto.FeignWxUserDto;
import com.wxzz.elearning.common.dto.SystemMessageMqDto;
import com.wxzz.elearning.common.exception.ServiceException;
import com.wxzz.elearning.common.utils.OpenFeignUtil;
import com.wxzz.elearning.common.vo.JgPageVo;
import com.wxzz.elearning.common.vo.ReturnVO;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service


public class DocentServiceImpl extends ServiceImpl<DocentMapper, Docent> implements IDocentService {


    @Autowired
    private DocentMapper docentMapper;

    @Autowired
    private WxUserMapper wxUserMapper;

    @Autowired
    private AdminUserMapper adminUserMapper;

    @Autowired
    private IAdminUserService adminUserService;

    @Autowired
    private ICurriculumApiFeign curriculumApiFeign;

    @Override
    public ReturnVO<JgPageVo<List<Docent>>> listDocent(Long enterpriseId, DocentDto docentDto) {
        PageHelper.startPage(docentDto.getCurPage(), docentDto.getMaxPage());
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("enterprise_id", enterpriseId);
        queryWrapper.orderByDesc("create_time");
        if (docentDto.getStatus() != null) {
            queryWrapper.eq("docent_status", docentDto.getStatus());
        }
        if (docentDto.getAppraisalStatus() != null) {
            queryWrapper.eq("appraisal_status", docentDto.getAppraisalStatus());
        }
        if (StringUtils.isNotBlank(docentDto.getDocentName())) {
            queryWrapper.like("docent_name", docentDto.getDocentName() + "%");
        }
        if (docentDto.getCommonCategoryId() != null) {
            queryWrapper.eq("common_category_id", docentDto.getCommonCategoryId());
        }
        if (docentDto.getIsFamous() != null) {
            queryWrapper.eq("is_famous", docentDto.getIsFamous());
        }
        List<Docent> docents = docentMapper.selectList(queryWrapper);
        for (Docent docent : docents) {
            //查询总讲数与学习人数
            ReturnVO<String> stringReturnVO = curriculumApiFeign.selectDocentById(docent.getId());
            if ("200".equals(stringReturnVO.getCode())) {
                JSONObject jsonObject = OpenFeignUtil.getJSONObject(stringReturnVO);
                docent.setAllCurriculumNum(jsonObject.getInteger("allCurriculumNum"));
                docent.setCurriculumStudyNum(jsonObject.getInteger("curriculumStudyNum"));
            }
            AdminUser adminUser = adminUserMapper.selectOne(new LambdaQueryWrapper<AdminUser>()
                    .eq(AdminUser::getDocentId, docent.getId()));
            if (adminUser != null) {
                docent.setUsername(adminUser.getUsername());
                docent.setPassword(adminUser.getPassword());
            }
            Integer platformLivetelecastTime = livetelecastApiFeign.selectPlatformLivetelecastTimeByDocentId(docent.getId());
            if (platformLivetelecastTime != null) {
                docent.setPlatformLivetelecastTime(platformLivetelecastTime / (60 * 60));
            }
            docent.setPlatformLivetelecastNum(livetelecastApiFeign.selectPlatformLivetelecastNumByDocentId(docent.getId()));
            //部门班组
            FeignWxUserDto feignWxUserDto = wxUserService.selectFeignWxUserDtoByDocentId(docent.getId());
            docent.setIdentityName(feignWxUserDto.getOrganizationName());
            docent.setOrganizationName(feignWxUserDto.getOrganizationName());
        }
        return new ReturnVO("讲师列表查询成功", new JgPageVo(new PageInfo<>(docents)));
    }

    @Override
    public ReturnVO deleteDocentById(Long docentId) {
        docentMapper.deleteById(docentId);
        return new ReturnVO("讲师列表查询成功", docentId);
    }

    @Autowired
    private ILivetelecastApiFeign livetelecastApiFeign;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private IAdminRoleService adminRoleService;

    @Transactional
    @Override
    public ReturnVO sendDocent(DocentInsDto docentInsDto) {
        WxUser wxUser = wxUserMapper.selectById(docentInsDto.getWxUserId());
        Optional.ofNullable(wxUser).orElseThrow(() -> new ServiceException("该微信用户已不存在"));
        if (docentInsDto.getId() == null) {
            AdminUserInsDto adminUserInsDto = new AdminUserInsDto();
            if (wxUser.getEnterpriseId() != null && wxUser.getEnterpriseId() != 0) {
                //只有企业才能发起试讲
                adminUserInsDto.setType(1);
            }
            Optional<Docent> docentOptional = docentMapper.selectOneByWxUserId(docentInsDto.getWxUserId());
            if (docentOptional.isPresent()) {
                throw new ServiceException("该用户已经申请过讲师端账号");
            }
            adminUserInsDto.setUsername(docentInsDto.getUsername());
            adminUserInsDto.setPassword(docentInsDto.getPassword());
            adminUserInsDto.setPhone(docentInsDto.getDocentPhone());
            ReturnVO<AdminUser> returnVO = adminUserService.saveAdminUser(wxUser.getEnterpriseId(), adminUserInsDto);
            AdminUser data = returnVO.getData();
            //关联讲师账号
            docentInsDto.setDocentName(wxUser.getNickname());
            docentInsDto.setWxUserId(docentInsDto.getWxUserId());
            docentInsDto.setEnterpriseId(wxUser.getEnterpriseId());
            //默认讲师状态通过 企业需要发起试讲
            docentInsDto.setDocentStatus(0);
            docentInsDto.setDocentPhone(wxUser.getPhone());

            if (wxUser.getEnterpriseId() != null && wxUser.getEnterpriseId() != 0) {
                //只有企业才能发起试讲
                //查看企业是否开启直接通过
                if (docentInsDto.getIsPass() != null && docentInsDto.getIsPass() == 1) {
                    docentInsDto.setAppraisalStatus(2);
                    docentInsDto.setDocentStatus(1);
                    wxUser.setIsDocent(1);
                    data.setIsDocent(1);
                    //添加正式讲师角色
                    adminRoleService.addTeacherRole(data.getId(), data.getEnterpriseId());
                } else {
                    //添加试讲讲师角色
                    adminRoleService.addTrialTeacherRole(data.getId(), data.getEnterpriseId());
                    data.setIsDocent(2);
                    wxUser.setIsDocent(2);
                }
                wxUser.setDocentUsername(data.getUsername());
                wxUser.setDocentPassword(data.getPassword());
                if (StringUtils.isNotBlank(wxUser.getToken())) {
                    if (redisTemplate.hasKey(wxUser.getToken())) {
                        //删除废弃token
                        redisTemplate.delete(wxUser.getToken());
                    }
                }
                //存放新的token
                String token = RedisConstants.WX_TOKEN + UUID.randomUUID().toString();
                wxUser.setToken(token);
                redisTemplate.opsForValue().set(token, JSONObject.toJSONString(wxUser), 60 * 60 * 24 * 10 * 30, TimeUnit.SECONDS);
                wxUserMapper.updateById(wxUser);
            }
            docentMapper.insert(docentInsDto);

            //修改为讲师端账号
            data.setRemark("该账号为讲师端账号");
            //data.setIsDocent(2);
            data.setDocentId(docentInsDto.getId());
            adminUserMapper.updateById(data);
            //发送消息
            SystemMessageMqDto systemMessageMqDto = new SystemMessageMqDto();
            if (docentInsDto.getIsSms() != null && docentInsDto.getIsSms() == 1) {
                systemMessageMqDto.setPhones(new ArrayList<String>() {
                    {
                        add(wxUser.getPhone());
                    }
                });
                systemMessageMqDto.setTemplateId(SmsConfig.saveDocentId);
                systemMessageMqDto.setParams(new ArrayList<String>() {
                    {
                        add(LocalDate.now().toString());
                        add(LocalDateTime.now().format(DateTimeFormatter.ofPattern("HH:mm:ss")));
                        add(docentInsDto.getUsername());
                        add(docentInsDto.getPassword());
                        //add(docentInsDto.getRemark());
                        add("无");
                    }
                });
            }
            systemMessageMqDto.setMessageDetail("恭喜你成为讲师,账号:" + docentInsDto.getUsername() + ",默认密码:" + docentInsDto.getPassword());
            systemMessageMqDto.setMessageTitle("创建讲师");
            systemMessageMqDto.setWxUserIds(new ArrayList<Long>() {
                {
                    add(wxUser.getId());
                }
            });
            userMessageProducer.ackMQSender(JSONObject.toJSONString(systemMessageMqDto));
        } else {
            //是否为封禁的操作
            boolean isBan = false;
            Docent docent = docentMapper.selectOne(new LambdaQueryWrapper<Docent>()
                    .eq(Docent::getWxUserId, docentInsDto.getWxUserId()));
            if (docent != null && !docent.getId().equals(docentInsDto.getId())) {
                throw new ServiceException("该微信用户已经绑定讲师");
            }
            if (docent != null && docent.getDocentStatus() != 2 && docentInsDto.getDocentStatus() != null && docentInsDto.getDocentStatus() == 2) {
                isBan = true;
            }
            AdminUser data = adminUserMapper.selectOne(new LambdaQueryWrapper<AdminUser>()
                    .eq(AdminUser::getDocentId, docentInsDto.getId()));
            //查看企业是否开启直接通过
            if (docentInsDto.getIsPass() != null && docentInsDto.getIsPass() == 1) {
                docentInsDto.setAppraisalStatus(2);
                docentInsDto.setDocentStatus(1);
                wxUser.setIsDocent(1);
                data.setIsDocent(1);
            } else {
                data.setIsDocent(2);
                wxUser.setIsDocent(2);
            }
            if (StringUtils.isNotBlank(wxUser.getToken())) {
                if (redisTemplate.hasKey(wxUser.getToken())) {
                    //删除废弃token
                    redisTemplate.delete(wxUser.getToken());
                }
            }
            //存放新的token
            String token = RedisConstants.WX_TOKEN + UUID.randomUUID().toString();
            wxUser.setToken(token);
            redisTemplate.opsForValue().set(token, JSONObject.toJSONString(wxUser), 60 * 60 * 24 * 10 * 30, TimeUnit.SECONDS);
            wxUserMapper.updateById(wxUser);
            adminUserMapper.updateById(data);
            docentMapper.updateById(docentInsDto);
            //发送封禁消息
            if (isBan) {
                //查询平台客服电话
                PlatformParam platformPhone = platformParamMapper.selectOne(new LambdaQueryWrapper<PlatformParam>()
                        .eq(PlatformParam::getParamKey, "platformPhone"));
                SystemMessageMqDto systemMessageMqDto = new SystemMessageMqDto();
                if (docentInsDto.getIsSms() != null && docentInsDto.getIsSms() == 1) {
                    systemMessageMqDto.setPhones(new ArrayList<String>() {
                        {
                            add(wxUser.getPhone());
                        }
                    });
                    systemMessageMqDto.setTemplateId(SmsConfig.docentBanId);
                    systemMessageMqDto.setParams(new ArrayList<String>() {
                        {
                            add(docent.getDocentName());
                            add(platformPhone.getParamDetail());
                        }
                    });
                }
                systemMessageMqDto.setMessageDetail("很抱歉,您在五星智造平台的" + docent.getDocentName() + "讲师身份已被封禁,详情请致客服" + platformPhone.getParamDetail());
                systemMessageMqDto.setMessageTitle("讲师封禁");
                systemMessageMqDto.setWxUserIds(new ArrayList<Long>() {
                    {
                        add(wxUser.getId());
                    }
                });
                userMessageProducer.ackMQSender(JSONObject.toJSONString(systemMessageMqDto));
            }
        }
        return new ReturnVO("账号创建成功,可用该账号登录讲师端试讲", docentInsDto);
    }

    @Autowired
    private PlatformParamMapper platformParamMapper;

    @Autowired
    private DocentApplyMapper docentApplyMapper;

    @Override
    public ReturnVO sendDocentApply(JSONObject jsonObject) {
        DocentApply docentApply = new DocentApply();
        docentApply.setWxUserId(jsonObject.getLong("id"));
        docentApply.setEnterpriseId(jsonObject.getLong("enterpriseId"));
        DocentApply result = docentApplyMapper.selectOne(new LambdaQueryWrapper<DocentApply>()
                .eq(DocentApply::getWxUserId, jsonObject.getLong("id"))
                .ne(DocentApply::getStatus, 2));
        if (result != null) {
            throw new ServiceException("已提交过申请");
        }
        docentApplyMapper.insert(docentApply);
        return new ReturnVO("申请提交成功", null);
    }

    @Override
    public ReturnVO selectStatus(Long wxUserId) {
        DocentApply docentApply = docentApplyMapper.selectOne(new LambdaQueryWrapper<DocentApply>()
                .eq(DocentApply::getWxUserId, wxUserId));
        if (docentApply != null) {
            return new ReturnVO("讲师申请状态查询成功", docentApply.getStatus());
        }
        return new ReturnVO("讲师申请状态查询成功", null);
    }

    @Autowired
    private EnterpriseMapper enterpriseMapper;

    @Override
    public ReturnVO passDocentApply(AdminUser adminUser, PassDocentApplyDto passDocentApplyDto) {
        DocentApply docentApply = docentApplyMapper.selectById(passDocentApplyDto.getDocentApplyId());
        Optional.ofNullable(docentApply).orElseThrow(() -> new ServiceException("该讲师申请已不存在"));
        DocentInsDto docentInsDto = new DocentInsDto();
        docentInsDto.setWxUserId(docentApply.getWxUserId());
        docentInsDto.setUsername(passDocentApplyDto.getUsername());
        docentInsDto.setPassword(passDocentApplyDto.getPassword());
        sendDocent(docentInsDto);
        docentApply.setStatus(1);
        docentApply.setCheckName(adminUser.getUsername());
        docentApply.setCheckPhone(adminUser.getPhone());
        docentApplyMapper.updateById(docentApply);
        //给予试讲讲师权限
        WxUser wxUser = wxUserMapper.selectById(docentApply.getWxUserId());
        if (wxUser != null) {
            Enterprise enterprise = enterpriseMapper.selectById(wxUser.getEnterpriseId());
            SystemMessageMqDto systemMessageMqDto = new SystemMessageMqDto();
            if (passDocentApplyDto.getIsSms() != null && passDocentApplyDto.getIsSms() == 1) {
                systemMessageMqDto.setPhones(new ArrayList<String>() {
                    {
                        add(wxUser.getPhone());
                    }
                });
                systemMessageMqDto.setTemplateId(SmsConfig.enterpriseDocentPassId);
                systemMessageMqDto.setParams(new ArrayList<String>() {
                    {
                        add(enterprise.getEnterpriseName());
                        add(LocalDate.now().toString());
                        add(LocalDateTime.now().format(DateTimeFormatter.ofPattern("HH:mm:ss")));
                        add(passDocentApplyDto.getUsername());
                        add(passDocentApplyDto.getPassword());
                        add(passDocentApplyDto.getRemark());
                    }
                });
            }
            systemMessageMqDto.setMessageDetail(passDocentApplyDto.getRemark());
            systemMessageMqDto.setMessageTitle("企业申请讲师-审核通过");
            systemMessageMqDto.setWxUserIds(new ArrayList<Long>() {
                {
                    add(wxUser.getId());
                }
            });
            userMessageProducer.ackMQSender(JSONObject.toJSONString(systemMessageMqDto));
        }
        return new ReturnVO("讲师申请审核通过", docentApply.getId());
    }

    @Autowired
    private UserMessageProducer userMessageProducer;

    @Override
    public ReturnVO failDocentApply(AdminUser adminUser, FailDocentApplyDto failDocentApplyDto) {
        DocentApply docentApply = docentApplyMapper.selectById(failDocentApplyDto.getDocentApplyId());
        Optional.ofNullable(docentApply).orElseThrow(() -> new ServiceException("该讲师申请已不存在"));
        docentApply.setStatus(2);
        docentApply.setCheckName(adminUser.getUsername());
        docentApply.setCheckPhone(adminUser.getPhone());
        docentApplyMapper.updateById(docentApply);
        WxUser wxUser = wxUserMapper.selectById(docentApply.getWxUserId());
        if (wxUser != null) {
            Enterprise enterprise = enterpriseMapper.selectById(wxUser.getEnterpriseId());
            SystemMessageMqDto systemMessageMqDto = new SystemMessageMqDto();
            if (failDocentApplyDto.getIsSms() != null && failDocentApplyDto.getIsSms() == 1) {
                systemMessageMqDto.setPhones(new ArrayList<String>() {
                    {
                        add(wxUser.getPhone());
                    }
                });
                systemMessageMqDto.setTemplateId(SmsConfig.enterpriseDocentFailId);
                systemMessageMqDto.setParams(new ArrayList<String>() {
                    {
                        add(enterprise.getEnterpriseName());
                        add(LocalDate.now().toString());
                        add(LocalDateTime.now().format(DateTimeFormatter.ofPattern("HH:mm:ss")));
                    }
                });
            }
            systemMessageMqDto.setMessageDetail(failDocentApplyDto.getReturnRemark());
            systemMessageMqDto.setMessageTitle("企业审核讲师-审核不通过");
            systemMessageMqDto.setWxUserIds(new ArrayList<Long>() {
                {
                    add(wxUser.getId());
                }
            });
            userMessageProducer.ackMQSender(JSONObject.toJSONString(systemMessageMqDto));
        }
        return new ReturnVO("讲师申请审核失败成功", docentApply.getId());
    }

    @Autowired
    private IWxUserService wxUserService;

    @Override
    public ReturnVO<JgPageVo<List<DocentApply>>> listDocentApply(Long enterpriseId, DocentApplyDto docentApplyDto) {
        PageHelper.startPage(docentApplyDto.getCurPage(), docentApplyDto.getMaxPage());
        QueryWrapper<DocentApply> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("create_time");
        queryWrapper.eq("enterprise_id", enterpriseId);
        if (docentApplyDto.getStatus() != null) {
            queryWrapper.eq("status", docentApplyDto.getStatus());
        }
        List<DocentApply> docentApplies = docentApplyMapper.selectList(queryWrapper);
        for (DocentApply docentApply : docentApplies) {
            FeignWxUserDto feignWxUserDto = wxUserService.selectFeignWxUserDtoByWxUserId(docentApply.getWxUserId());
            if (feignWxUserDto != null) {
                docentApply.setIcon(feignWxUserDto.getIcon());
                docentApply.setNickname(feignWxUserDto.getNickname());
                docentApply.setOrganizationName(feignWxUserDto.getOrganizationName());
                docentApply.setLastOrganizationName(feignWxUserDto.getLastOrganizationName());
            }
        }
        return new ReturnVO("讲师申请状态查询成功", new JgPageVo<>(new PageInfo(docentApplies)));
    }

    @Override
    public ReturnVO listDocentAllEnterprise(DocentApplyDto docentApplyDto) {
        PageHelper.startPage(docentApplyDto.getCurPage(), docentApplyDto.getMaxPage());
        QueryWrapper<Docent> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("create_time");
        queryWrapper.ne("enterprise_id", 0);
        if (StringUtils.isNotBlank(docentApplyDto.getDocentName())) {
            queryWrapper.like("docent_name", docentApplyDto.getDocentName() + "%");
        }
        if (docentApplyDto.getStatus() != null) {
            queryWrapper.eq("docent_status", docentApplyDto.getStatus());
        }
        List<Docent> docents = docentMapper.selectList(queryWrapper);
        for (Docent docent : docents) {
            Enterprise enterprise = enterpriseMapper.selectById(docent.getEnterpriseId());
            if (enterprise != null) {
                docent.setEnterpriseName(enterprise.getEnterpriseName());
            }
        }
        return new ReturnVO("讲师列表查询成功", new JgPageVo<>(new PageInfo(docents)));
    }

    @Override
    public ReturnVO saveDocent(DocentInsDto docentInsDto) {
        if (docentInsDto.getWxUserId() != null) {
            throw new ServiceException("平台讲师不能绑定微信用户");
        }
        if (docentInsDto.getId() == null) {
            AdminUserInsDto adminUserInsDto = new AdminUserInsDto();
            adminUserInsDto.setUsername(docentInsDto.getUsername());
            adminUserInsDto.setPassword(docentInsDto.getPassword());
            adminUserInsDto.setPhone(docentInsDto.getDocentPhone());
            ReturnVO<AdminUser> returnVO = adminUserService.saveAdminUser(0L, adminUserInsDto);
            AdminUser data = returnVO.getData();
            //关联讲师账号
            //docentInsDto.setDocentName("平台讲师");
            docentInsDto.setWxUserId(docentInsDto.getWxUserId());
            docentInsDto.setEnterpriseId(0L);
            //默认讲师状态通过 企业需要发起试讲
            docentInsDto.setDocentStatus(1);
            docentMapper.insert(docentInsDto);
            //修改为讲师端账号
            data.setRemark("该账号为讲师端账号");
            data.setIsDocent(1);
            data.setDocentId(docentInsDto.getId());
            adminUserMapper.updateById(data);
            adminRoleService.addTeacherRole(data.getId(), data.getEnterpriseId());
            //发送短信
            SystemMessageMqDto systemMessageMqDto = new SystemMessageMqDto();
            if (docentInsDto.getIsSms() != null && docentInsDto.getIsSms() == 1) {
                systemMessageMqDto.setPhones(new ArrayList<String>() {
                    {
                        add(docentInsDto.getDocentPhone());
                    }
                });
                systemMessageMqDto.setTemplateId(SmsConfig.saveDocentId);
                systemMessageMqDto.setParams(new ArrayList<String>() {
                    {
                        add(LocalDate.now().toString());
                        add(LocalDateTime.now().format(DateTimeFormatter.ofPattern("HH:mm:ss")));
                        add(docentInsDto.getUsername());
                        add(docentInsDto.getPassword());
                        //add(docentInsDto.getRemark());
                        add("无");
                    }
                });
            }
            userMessageProducer.ackMQSender(JSONObject.toJSONString(systemMessageMqDto));
        } else {
            Docent docent = new Docent();
            BeanUtils.copyProperties(docentInsDto, docent);
            docentMapper.updateById(docent);
        }
        return new ReturnVO("账号创建成功", docentInsDto);
    }

    @Override
    public ReturnVO updateDocentDetail(Docent docent) {
        docentMapper.updateById(docent);
        return new ReturnVO("修改讲师介绍", docent.getId());
    }

    @Autowired
    private DocentTrialMapper docentTrialMapper;

    @Override
    public ReturnVO saveDocentTrial(DocentTrial docentTrial) {
        //课件
        if (docentTrial.getDocentTrialFileVos() != null) {
            StringBuilder platformLivetelecastFiles = new StringBuilder();
            StringBuilder platformLivetelecastFileNames = new StringBuilder();
            StringBuilder platformLivetelecastFileSizes = new StringBuilder();
            for (DocentTrialFileVo docentTrialFileVo : docentTrial.getDocentTrialFileVos()) {
                platformLivetelecastFiles.append(docentTrialFileVo.getTrialFile()).append(",");
                platformLivetelecastFileNames.append(docentTrialFileVo.getTrialFileName()).append(",");
                platformLivetelecastFileSizes.append(docentTrialFileVo.getTrialFileSize()).append(",");
            }
            docentTrial.setTrialFile(platformLivetelecastFiles.toString());
            docentTrial.setTrialFileName(platformLivetelecastFileNames.toString());
            docentTrial.setTrialFileSize(platformLivetelecastFileSizes.toString());
        }
        if (docentTrial.getId() == null) {
            if (docentTrial.getDocentId() == null) {
                throw new ServiceException("请选择讲师");
            }
            Docent docent = docentMapper.selectById(docentTrial.getDocentId());
            if (docent == null) {
                throw new ServiceException("该讲师不存在");
            }
            docent.setTrialNum(docent.getTrialNum() + 1);
            docent.setTrialUpdateTime(LocalDateTime.now());
            docentMapper.updateById(docent);
            docentTrialMapper.insert(docentTrial);
        } else {
            docentTrialMapper.updateById(docentTrial);
        }
        return new ReturnVO("发布试讲成功", docentTrial.getId());
    }

    @Override
    public ReturnVO<JgPageVo<List<DocentTrial>>> listDocentTrial(Integer trialType, DocentTrialDto docentTrialDto) {
        if (docentTrialDto.getDocentId() == null) {
            throw new ServiceException("请传入讲师id");
        }
        PageHelper.startPage(docentTrialDto.getCurPage(), docentTrialDto.getMaxPage());
        List<DocentTrial> docentTrials = docentTrialMapper.selectList(new LambdaQueryWrapper<DocentTrial>()
                .eq(DocentTrial::getDocentId, docentTrialDto.getDocentId()).eq(DocentTrial::getTrialType, trialType));
        return new ReturnVO("试讲列表查询成功", new JgPageVo<>(new PageInfo(docentTrials)));
    }

    @Override
    public ReturnVO<JgPageVo<List<DocentTrial>>> wxListDocentTrial(Integer trialType, Long wxUserId, WxDocentTrialDto wxDocentTrialDto) {
        Optional<Docent> docentOptional = docentMapper.selectOneByWxUserId(wxUserId);
        if (!docentOptional.isPresent()) {
            return new ReturnVO("试讲列表查询成功", new JgPageVo<>(new PageInfo(new ArrayList())));
        }
        PageHelper.startPage(wxDocentTrialDto.getCurPage(), wxDocentTrialDto.getMaxPage());
        List<DocentTrial> docentTrials = docentTrialMapper.selectList(new LambdaQueryWrapper<DocentTrial>()
                .eq(DocentTrial::getDocentId, docentOptional.get().getId()).eq(DocentTrial::getTrialType, trialType));
        return new ReturnVO("试讲列表查询成功", new JgPageVo<>(new PageInfo(docentTrials)));
    }

    @Override
    public ReturnVO<DocentTrial> selectDocentTrialDetail(Long docentTrialId) {
        DocentTrial docentTrial = docentTrialMapper.selectById(docentTrialId);
        //课件
        if (docentTrial != null && StringUtils.isNotBlank(docentTrial.getTrialFile())) {
            if (docentTrial.getTrialFile() != null && docentTrial.getTrialFileName() != null && docentTrial.getTrialFileSize() != null) {
                String[] files = docentTrial.getTrialFile().split(",");
                String[] fileNames = docentTrial.getTrialFileName().split(",");
                String[] fileSizes = docentTrial.getTrialFileSize().split(",");
                List<DocentTrialFileVo> platformLivetelecastFileVos = Lists.newArrayList();
                for (int i = 0; i < files.length; i++) {
                    DocentTrialFileVo curriculumFileVo = new DocentTrialFileVo();
                    curriculumFileVo.setTrialFile(files[i]);
                    curriculumFileVo.setTrialFileName(fileNames[i]);
                    curriculumFileVo.setTrialFileSize(fileSizes[i]);
                    platformLivetelecastFileVos.add(curriculumFileVo);
                }
                docentTrial.setDocentTrialFileVos(platformLivetelecastFileVos);
            }
        }
        return new ReturnVO("试讲/晋升详情查询成功", docentTrial);
    }

    @Override
    public ReturnVO<DocentTool> selectDocentToolDetail(Long docentToolId) {
        DocentTool docentTool = docentToolMapper.selectById(docentToolId);
        //课件
        if (docentTool != null && StringUtils.isNotBlank(docentTool.getUrl())) {
            if (docentTool.getUrl() != null && docentTool.getFileName() != null && docentTool.getFileSize() != null) {
                String[] files = docentTool.getUrl().split(",");
                String[] fileNames = docentTool.getFileName().split(",");
                String[] fileSizes = docentTool.getFileSize().split(",");
                List<DocentToolFileVo> platformLivetelecastFileVos = Lists.newArrayList();
                for (int i = 0; i < files.length; i++) {
                    DocentToolFileVo curriculumFileVo = new DocentToolFileVo();
                    curriculumFileVo.setUrl(files[i]);
                    curriculumFileVo.setFileName(fileNames[i]);
                    curriculumFileVo.setFileSize(fileSizes[i]);
                    platformLivetelecastFileVos.add(curriculumFileVo);
                }
                docentTool.setDocentToolFileVoList(platformLivetelecastFileVos);
            }
        }
        return new ReturnVO("讲师工具详情查询成功", docentTool);
    }

    @Transactional
    @Override
    public ReturnVO sendDocentTrialToPromotion(Long docentTrialId) {
        DocentTrial docentTrial = docentTrialMapper.selectById(docentTrialId);
        if (docentTrial == null) {
            throw new ServiceException("该试讲已不存在");
        }
        docentTrial.setTrialType(1);
        docentTrialMapper.updateById(docentTrial);
        //讲师状态变为评审中
        Docent docent = docentMapper.selectById(docentTrial.getDocentId());
        Optional.ofNullable(docent).orElseThrow(() -> new ServiceException("该讲师已经不存在"));
        docent.setDocentStatus(1);
        docentMapper.updateById(docent);
        return new ReturnVO("发布晋升成功", docentTrialId);
    }

    @Autowired
    private DocentToolMapper docentToolMapper;

    @Override
    public ReturnVO<JgPageVo<List<DocentTool>>> listDocentTool(Long enterpriseId, DocentToolDto docentToolDto) {
        PageHelper.startPage(docentToolDto.getCurPage(), docentToolDto.getMaxPage());
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.orderByDesc("create_time");
        queryWrapper.eq("enterprise_id", enterpriseId);
        if (StringUtils.isNotBlank(docentToolDto.getToolName())) {
            queryWrapper.like("tool_name", docentToolDto.getToolName() + "%");
        }
        if (docentToolDto.getFileType() != null) {
            queryWrapper.eq("file_type", docentToolDto.getFileType());
        }
        List<DocentTool> docentTools = docentToolMapper.selectList(queryWrapper);
        return new ReturnVO("讲师工具列表查询成功", new JgPageVo<>(new PageInfo(docentTools)));
    }

    @Override
    public ReturnVO saveDocentTool(DocentTool docentTool) {
        if (docentTool.getDocentToolFileVoList() != null) {
            StringBuilder platformLivetelecastFiles = new StringBuilder();
            StringBuilder platformLivetelecastFileNames = new StringBuilder();
            StringBuilder platformLivetelecastFileSizes = new StringBuilder();
            for (DocentToolFileVo docentToolFileVo : docentTool.getDocentToolFileVoList()) {
                platformLivetelecastFiles.append(docentToolFileVo.getUrl()).append(",");
                platformLivetelecastFileNames.append(docentToolFileVo.getFileName()).append(",");
                platformLivetelecastFileSizes.append(docentToolFileVo.getFileSize()).append(",");
            }
            docentTool.setUrl(platformLivetelecastFiles.toString());
            docentTool.setFileName(platformLivetelecastFileNames.toString());
            docentTool.setFileSize(platformLivetelecastFileSizes.toString());
        }
        if (docentTool.getId() == null) {
            docentToolMapper.insert(docentTool);
        } else {
            docentToolMapper.updateById(docentTool);
        }
        return new ReturnVO("讲师工具添加成功", docentTool.getId());
    }

    @Override
    public ReturnVO updateDocentTool(DocentTool docentTool) {
        docentToolMapper.updateById(docentTool);
        return new ReturnVO("讲师工具修改成功", docentTool.getId());
    }

    @Override
    public ReturnVO selectDocentById(Long docentId) {
        Docent docent = docentMapper.selectById(docentId);
        return new ReturnVO("讲师详情查询成功", JSONObject.toJSONString(docent));
    }

    @Override
    public ReturnVO<Docent> selectDocentById4mini(Long docentId) {
        Docent docent = docentMapper.selectById(docentId);
        Optional.ofNullable(docent).orElseThrow(() -> new ServiceException("讲师不存在"));
        //查询总讲数与学习人数
        ReturnVO<String> stringReturnVO = curriculumApiFeign.selectDocentById(docent.getId());
        if ("200".equals(stringReturnVO.getCode())) {
            JSONObject jsonObject = OpenFeignUtil.getJSONObject(stringReturnVO);
            docent.setAllCurriculumNum(jsonObject.getInteger("allCurriculumNum"));
            docent.setCurriculumStudyNum(jsonObject.getInteger("curriculumStudyNum"));
        }
        return new ReturnVO("讲师详情查询成功", docent);
    }

    @Override
    public ReturnVO<Docent> selectDocentDetail(Long docentId) {
        Docent docent = docentMapper.selectById(docentId);
        Optional.ofNullable(docent).orElseThrow(() -> new ServiceException("讲师不存在"));
        //查询总讲数与学习人数
        ReturnVO<String> stringReturnVO = curriculumApiFeign.selectDocentById(docent.getId());
        if ("200".equals(stringReturnVO.getCode())) {
            JSONObject jsonObject = OpenFeignUtil.getJSONObject(stringReturnVO);
            docent.setAllCurriculumNum(jsonObject.getInteger("allCurriculumNum"));
            docent.setCurriculumStudyNum(jsonObject.getInteger("curriculumStudyNum"));
        }
        AdminUser adminUser = adminUserMapper.selectOne(new LambdaQueryWrapper<AdminUser>()
                .eq(AdminUser::getDocentId, docent.getId()));
        if (adminUser != null) {
            docent.setUsername(adminUser.getUsername());
            docent.setPassword(adminUser.getPassword());
        }
        return new ReturnVO("讲师详情查询成功", docent);
    }

    @Autowired
    private IUserWalletApiFeign userWalletApiFeign;

    @Override
    public ReturnVO<Docent> selectMyWallet(Long docentId) {
        Docent docent = docentMapper.selectById(docentId);
        if (docent == null) {
            throw new ServiceException("您不是讲师账号");
        }
        FeignUserWalletDto feignUserWalletDto = userWalletApiFeign.selectUserWalletByUserIdAndType(docentId, 2);
        docent.setUserBalance(feignUserWalletDto.getUserBalance());
        docent.setAccumulate(feignUserWalletDto.getAccumulate());
        return new ReturnVO("查询我的账户成功", docent);
    }


    @Transactional
    @Override
    public ReturnVO updateDocentTrial(UpdateDocentTrialDto updateDocentTrialDto) {
        DocentTrial docentTrial = docentTrialMapper.selectById(updateDocentTrialDto.getDocentTrialId());
        Optional.ofNullable(docentTrial).orElseThrow(() -> new ServiceException("该晋升不存在"));
        docentTrial.setScore(updateDocentTrialDto.getScore());
        if (updateDocentTrialDto.getAppraisalStatus() != null && updateDocentTrialDto.getAppraisalStatus() == 2) {
            //修改讲师的状态
            Docent docent = docentMapper.selectById(docentTrial.getDocentId());
            Optional.ofNullable(docent).orElseThrow(() -> new ServiceException("讲师不存在"));
            docent.setAppraisalStatus(2);
            docent.setDocentStatus(1);
            docentMapper.updateById(docent);
            //修改用户的状态
            AdminUser adminUser = adminUserMapper.selectOne(new LambdaQueryWrapper<AdminUser>()
                    .eq(AdminUser::getDocentId, docent.getId()));
            adminUser.setIsDocent(1);
            adminUserMapper.updateById(adminUser);
            //修改小程序端用户状态
            WxUser wxUser = wxUserMapper.selectById(docent.getWxUserId());
            if (StringUtils.isNotBlank(wxUser.getToken())) {
                if (redisTemplate.hasKey(wxUser.getToken())) {
                    //删除废弃token
                    redisTemplate.delete(wxUser.getToken());
                }
            }
            //存放新的token
            String token = RedisConstants.WX_TOKEN + UUID.randomUUID().toString();
            wxUser.setToken(token);
            redisTemplate.opsForValue().set(token, JSONObject.toJSONString(wxUser), 60 * 60 * 24 * 10 * 30, TimeUnit.SECONDS);
            wxUserMapper.updateById(wxUser);
        }
        docentTrialMapper.updateById(docentTrial);
        return new ReturnVO("修改晋升状态", docentTrial.getId());
    }

    @Override
    public Integer countByPlatformDocentNum() {
        return docentMapper.selectCount(new LambdaQueryWrapper<Docent>()
                .eq(Docent::getEnterpriseId, 0));
    }

    @Override
    public Integer countByEnterpriseDocentNum() {
        return docentMapper.selectCount(new LambdaQueryWrapper<Docent>()
                .ne(Docent::getEnterpriseId, 0));
    }

    @Override
    public Integer selectCountByDocent(Long enterpriseId) {
        return docentMapper.selectCount(new LambdaQueryWrapper<Docent>().eq(Docent::getEnterpriseId, enterpriseId));
    }

}
